package com.jy.rhin.application.infra;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jy.rhin.application.infra.event.Event4DocumentEntry;
import com.jy.rhin.application.infra.event.Event4DocumentReference;
import com.jy.rhin.config.infra.RhinRabbitConfig;
import com.jy.rhin.infra.repo.document.submission.query.DocumentSubmissionQueryHandler;
import com.jy.rhin.sdk.dto.notification.NotificationMessageDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author dhl
 * @date 2022/7/18
 * @Description
 */
@Slf4j
@Service
public class SendMessageApplicationService {

    @Value("${spring.application.name}")
    private String serviceName;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RhinRabbitConfig.RhinRabbitConfigurationProperties rhinRabbitProperties;
    @Resource
    private DocumentSubmissionQueryHandler submissionQueryHandler;
    private static final String DOCUMENT_REFERENCE = "rhin:documentReference";
    private static final String DOCUMENT_ENTRY = "rhin:documentEntry";

    /**
     * 文档提交-索引消息
     */
    @EventListener
    public void publishMessageEventHandler(Event4DocumentReference event) {
        JSONObject json = JSON.parseObject(JSON.toJSON(event).toString());
        JSONObject message = new JSONObject();
        message.put("topicExp", DOCUMENT_REFERENCE);
        message.put("documentReference", json);
        sendMessage(message);
    }

    /**
     * 文档注册-条目消息
     */
    @EventListener
    public void publishMessageEventHandler(Event4DocumentEntry event) {
        Long submissionSetId = event.getSubmissionSetId();
        String setJsonText = submissionQueryHandler.querySubmissionSetJsonText(submissionSetId);
        if (StringUtils.isEmpty(setJsonText)) {
            log.error("文档集数据不存在--- submissionSetId：{}", submissionSetId);
            return;
        }
        setJsonText = submissionSetContentSimplify(setJsonText);
        List<String> entryJsonTextList = submissionQueryHandler.queryEntryJsonTextListBySubmissionSetId(submissionSetId);
        if (CollectionUtils.isEmpty(entryJsonTextList)) {
            log.error("文档元数据不存在--- submissionSetId：{}", submissionSetId);
            return;
        }
        for (String entryJsonText : entryJsonTextList) {
            JSONObject message = new JSONObject();
            message.put("topicExp", DOCUMENT_ENTRY);
            message.put("submissionSet", JSON.parseObject(setJsonText));
            message.put("documentEntry", JSON.parseObject(entryJsonText));
            sendMessage(message);
        }
    }

    /**
     * 文档提交集元数据简化 去除消息不需要的内容
     *
     * @param setJsonText
     * @return
     */
    private String submissionSetContentSimplify(String setJsonText) {
        JSONObject jsonObject = JSON.parseObject(setJsonText);
        jsonObject.remove("folderList");
        jsonObject.remove("associationList");
        jsonObject.remove("documentEntryList");
        jsonObject.remove("folderOrDocumentEntryOrAssociation");
        return jsonObject.toJSONString();
    }


    /**
     * 发送mq消息
     *
     * @param jsonObject
     */
    private void sendMessage(JSONObject jsonObject) {
        String data = NotificationMessageDto.builder()
                .sender(serviceName)
                .data(jsonObject)
                .build();
        rabbitTemplate.convertAndSend(rhinRabbitProperties.getExchange(), rhinRabbitProperties.getDocumentProviderAndRegisterRoutingKey(), data);
    }
}
